import React, { useState, useEffect } from 'react';
import { Modal, Tabs, Button, Space, Progress, message, Typography } from 'antd';
import { FileTextOutlined, FilePdfOutlined, DownloadOutlined } from '@ant-design/icons';
import { PDFExportConfig } from './PDFExportConfig';
import { WordExportConfig } from './WordExportConfig';
import { ExportHistory } from './ExportHistory';
import { exportService } from '../../../services/export/exportService';
import { 
  PDFExportOptions, 
  WordExportOptions, 
  ExportProgress, 
  DEFAULT_PDF_OPTIONS, 
  DEFAULT_WORD_OPTIONS 
} from '../../../services/export/types';

const { Title, Text } = Typography;

interface ExportPanelProps {
  visible: boolean;
  content: string;
  onClose: () => void;
  onExportComplete?: (filename: string, format: string) => void;
}

export const ExportPanel: React.FC<ExportPanelProps> = ({
  visible,
  content,
  onClose,
  onExportComplete
}) => {
  const [activeTab, setActiveTab] = useState<string>('pdf');
  const [pdfOptions, setPdfOptions] = useState<PDFExportOptions>(DEFAULT_PDF_OPTIONS);
  const [wordOptions, setWordOptions] = useState<WordExportOptions>(DEFAULT_WORD_OPTIONS);
  const [isExporting, setIsExporting] = useState(false);
  const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);
  const [filename, setFilename] = useState('');

  // 加载用户保存的设置
  useEffect(() => {
    if (visible) {
      loadUserSettings();
      generateDefaultFilename();
    }
  }, [visible]);

  const loadUserSettings = async () => {
    try {
      const [pdfSettings, wordSettings] = await Promise.all([
        exportService.getUserPDFSettings(),
        exportService.getUserWordSettings()
      ]);

      setPdfOptions(prevOptions => ({ ...prevOptions, ...pdfSettings }));
      setWordOptions(prevOptions => ({ ...prevOptions, ...wordSettings }));
    } catch (error) {
      console.error('[ExportPanel] 加载用户设置失败:', error);
    }
  };

  const generateDefaultFilename = () => {
    const now = new Date();
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0');
    setFilename(`文档_${timestamp}`);
  };

  const handleExport = async () => {
    if (!content.trim()) {
      message.warning('文档内容为空，无法导出');
      return;
    }

    if (!filename.trim()) {
      message.warning('请输入文件名');
      return;
    }

    setIsExporting(true);
    setExportProgress(null);

    // 创建带进度回调的导出服务
    const progressService = exportService;
    progressService['progressCallback'] = setExportProgress;

    try {
      let result;
      
      if (activeTab === 'pdf') {
        // 保存PDF设置
        await exportService.saveUserPDFSettings(pdfOptions);
        result = await exportService.exportToPDF(content, pdfOptions, filename);
      } else {
        // 保存Word设置
        await exportService.saveUserWordSettings(wordOptions);
        result = await exportService.exportToWord(content, wordOptions, filename);
      }

      if (result.success) {
        message.success(`导出成功: ${result.filename}`);
        onExportComplete?.(result.filename!, activeTab);
        
        // 延迟关闭，让用户看到成功消息
        setTimeout(() => {
          onClose();
        }, 1500);
      } else {
        message.error(`导出失败: ${result.error}`);
      }
    } catch (error) {
      console.error('[ExportPanel] 导出失败:', error);
      message.error('导出失败，请重试');
    } finally {
      setIsExporting(false);
      setExportProgress(null);
    }
  };

  const handlePreview = async () => {
    try {
      const options = activeTab === 'pdf' ? pdfOptions : wordOptions;
      const previewUrl = await exportService.previewExport(content, activeTab as 'pdf' | 'word', options);
      
      if (previewUrl) {
        // 打开预览窗口
        window.open(previewUrl, '_blank');
      } else {
        message.info('预览功能暂未实现');
      }
    } catch (error) {
      console.error('[ExportPanel] 预览失败:', error);
      message.error('预览失败');
    }
  };

  const tabItems = [
    {
      key: 'pdf',
      label: (
        <Space>
          <FilePdfOutlined />
          PDF导出
        </Space>
      ),
      children: (
        <PDFExportConfig
          options={pdfOptions}
          onChange={setPdfOptions}
          filename={filename}
          onFilenameChange={setFilename}
          disabled={isExporting}
        />
      )
    },
    {
      key: 'word',
      label: (
        <Space>
          <FileTextOutlined />
          Word导出
        </Space>
      ),
      children: (
        <WordExportConfig
          options={wordOptions}
          onChange={setWordOptions}
          filename={filename}
          onFilenameChange={setFilename}
          disabled={isExporting}
        />
      )
    },
    {
      key: 'history',
      label: '导出历史',
      children: <ExportHistory />
    }
  ];

  const getProgressColor = () => {
    if (!exportProgress) return 'blue';
    switch (exportProgress.stage) {
      case 'preparing': return 'blue';
      case 'converting': return 'orange';
      case 'generating': return 'purple';
      case 'saving': return 'green';
      case 'completed': return 'green';
      default: return 'blue';
    }
  };

  return (
    <Modal
      title={
        <Title level={4} style={{ margin: 0 }}>
          <DownloadOutlined style={{ marginRight: 8 }} />
          文档导出
        </Title>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      styles={{ body: { maxHeight: '70vh', overflowY: 'auto' } }}
      footer={
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            {exportProgress && (
              <div>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  {exportProgress.message}
                </Text>
                <Progress
                  percent={exportProgress.progress}
                  strokeColor={getProgressColor()}
                  size="small"
                  showInfo={false}
                  style={{ marginTop: 4 }}
                />
              </div>
            )}
          </div>
          <Space>
            <Button onClick={onClose} disabled={isExporting}>
              取消
            </Button>
            {activeTab !== 'history' && (
              <>
                <Button onClick={handlePreview} disabled={isExporting || !content.trim()}>
                  预览
                </Button>
                <Button
                  type="primary"
                  icon={activeTab === 'pdf' ? <FilePdfOutlined /> : <FileTextOutlined />}
                  loading={isExporting}
                  onClick={handleExport}
                  disabled={!content.trim() || !filename.trim()}
                >
                  {isExporting ? '导出中...' : `导出${activeTab.toUpperCase()}`}
                </Button>
              </>
            )}
          </Space>
        </div>
      }
    >
      <div style={{ minHeight: 400 }}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </div>
    </Modal>
  );
};